﻿'This Class shall be in the Meta SDK V4 in the Processing Layer.
'Class factory to be created.
Namespace PL.MetaSDK 'Processing Layer

    Public Class MetaCommand_PL
        Inherits PLBase
        Implements IPLProcess



        Private ReadOnly CST_PivotLayoutTYPEId As Guid = New Guid("{ED88994E-FBE6-45ba-8678-521A16640826}")
        Private _aQueryName As String

        Public Sub New()
            MyBase.New()
        End Sub

        Public Sub New(ByVal queryName As String)
            MyBase.New(queryName)
            _aQueryName = queryName
        End Sub
        ''' <summary>
        ''' Generate Columns from a MetaQuery, MetaQuery type is SP
        ''' </summary>
        ''' <param name="queryName"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GenerateColumnsFromSP(ByVal queryName As String) As Boolean
            Try
                Dim mq As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
                Dim sqlCmd As SqlCommand = MetaQuery.GetSPCmdByMeta(mq)
                Dim mc As MetaDataTable = New MetaDataTable ' the set of columns for that Metaquery
                Dim aQueryId As Guid
                Dim colPosition As Integer = 0

                Dim indexrow As Integer
                Dim arow As DataRow
                aQueryId = mq.QueryID
                mc.QueryName = "MetaColumns"
                mc.GetMetaCommand()
                mc.MetaCommand.SQLWhere = String.Format("QueryId_FK = '{0}'", aQueryId.ToString)
                mc.FillBusinessApplicationData()
                mc.DefaultView.Sort = "ColumnName"
                For Each col As SqlParameter In sqlCmd.Parameters
                    indexrow = mc.DefaultView.Find(col.ParameterName)
                    If indexrow = -1 AndAlso (col.Direction = ParameterDirection.Input Or col.Direction = ParameterDirection.InputOutput) Then
                        arow = mc.NewRow()
                        'assign value for the metacolumn here

                        arow("ColumnID") = Guid.NewGuid()
                        arow("QueryID_FK") = aQueryId
                        arow("LayoutID_FK") = CommonExt.Base.IdRepository.META_METALAYOUT_DEFAULT
                        arow("ColumnName") = col.ParameterName
                        arow("Split") = 0
                        arow("pCaption_StringID_FK") = DBNull.Value
                        arow("RoundTypeID_FK") = DBNull.Value
                        arow("RoundFactor") = 0
                        arow("pNumberFormatID_FK") = DBNull.Value
                        arow("pNumberFormat") = ""
                        arow("LOVQueryID_FK") = DBNull.Value
                        arow("LOVAllowSharing") = False
                        arow("TranslateQueryID_FK") = DBNull.Value
                        arow("TRAllowSharing") = False
                        arow("SubQueryID_FK") = DBNull.Value
                        arow("pAlignment") = "3"
                        arow("pAllowFocus") = True
                        arow("pAllowSizing") = True
                        arow("pAutoCompletion") = False
                        arow("pAutoDropDown") = False
                        arow("pBackColor") = ""
                        arow("pButton") = False
                        arow("pButtonPicture") = 0
                        'DataWidth
                        If col.DbType = DbType.String Or col.DbType = DbType.StringFixedLength Or col.DbType = DbType.AnsiString Or col.DbType = DbType.AnsiStringFixedLength Then
                            arow("pDataWidth") = IIf(col.Size >= Int16.MaxValue, Int16.MaxValue, col.Size)
                        ElseIf col.DbType = DbType.Boolean Then
                            arow("pDataWidth") = 1
                        Else
                            arow("pDataWidth") = 0
                        End If
                        arow("pDefaultValue") = DBNull.Value
                        arow("pEditMask") = ""
                        arow("pEditMaskRight") = False
                        arow("pEditMaskUpdate") = False
                        arow("pHeadAlignment") = 3
                        arow("pLocked") = False
                        arow("pMerge") = False
                        arow("pOrder") = colPosition
                        arow("pPresentation") = 0
                        arow("pVisible") = 1
                        arow("pWidth") = 200
                        arow("pAllowGroupBy") = False
                        arow("pGroupByOrder") = -1
                        arow("SystemRecord") = True
                        arow("ColumnGroupID_FK") = Base.IdRepository.METALIST_METACOLUMNGROUPE_PARAMETER
                        arow("pDataTypeID_FK") = IdRepository.SqlDbTypeToGUID(sqlCmd.Parameters(col.ParameterName).SqlDbType.ToString.ToLower)
                        'arow("Crtd_DT") = Now()
                        'arow("Crtd_UId") = ""
                        'arow("LUpd_DT") = Now()
                        'arow("LUpd_UId") = ""
                        'arow("RecordVersion") = ""

                        'ID, Cd, _PRM, _ALT, Inactive?
                        If col.ParameterName = "RecordVersion" Then
                            arow("pAllowSizing") = False
                            arow("pVisible") = 0
                        ElseIf col.ParameterName.ToUpper.EndsWith("CD") Then
                            arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_CODE
                        ElseIf col.ParameterName.ToUpper.EndsWith("_PRM") Then
                            arow("pAllowSizing") = 1
                            If mq.QueryName.ToUpper.StartsWith("LOV_") Then
                                arow("pVisible") = 2
                                arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_DESCRIPTION
                            Else
                                arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_DESCRIPTION_PRM
                            End If
                        ElseIf col.ParameterName.ToUpper.EndsWith("_ALT") Then
                            If mq.QueryName.ToUpper.StartsWith("LOV_") Then
                                arow("pVisible") = 2
                                arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_DESCRIPTION
                            Else
                                arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_DESCRIPTION_ALT
                            End If
                        ElseIf col.ParameterName.ToUpper.EndsWith("INACTIVE") Then
                            arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_INACTIVE
                        End If

                        If col.ParameterName.ToUpper.EndsWith("CRTD_DT") Then
                            arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_CRTD_DT
                        ElseIf col.ParameterName.ToUpper.EndsWith("CRTD_UID") Then
                            arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_CRTD_UID
                        ElseIf col.ParameterName.ToUpper.EndsWith("LUPD_DT") Then
                            arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_LUPD_DT
                        ElseIf col.ParameterName.ToUpper.EndsWith("LUPD_UID") Then
                            arow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_LUPD_UID
                        End If
                        '
                        mc.Rows.Add(arow)
                        colPosition = colPosition + 1
                    Else
                        If indexrow > -1 Then
                            arow = mc.DefaultView.Item(indexrow).Row
                            arow("pDataTypeID_FK") = IdRepository.SqlDbTypeToGUID(sqlCmd.Parameters(col.ParameterName).SqlDbType.ToString.ToLower)
                        End If
                    End If
                Next
                'Scan for extra columns, not in the metaquery and delete it. 
                Dim row As DataRow
                Dim found As Boolean
                For ii As Integer = 0 To mc.Rows.Count - 1
                    row = mc.Rows(ii)
                    found = False
                    For Each col As SqlParameter In sqlCmd.Parameters
                        If row("ColumnName") = col.ParameterName Then
                            found = True
                        End If
                    Next
                    If Not found AndAlso row("ColumnGroupID_FK") = Base.IdRepository.METALIST_METACOLUMNGROUPE_PARAMETER Then
                        row.Delete()
                    End If
                Next
                mc.ApplyChanges(reload:=False)
                Return True
            Catch ex As Exception
                Throw ex
                Return False
            End Try
        End Function

        ''' <summary>
        ''' ReOrder the Columns position, from 0 to x columns 
        ''' </summary>
        ''' <param name="mc"></param>
        ''' <remarks>It will be reorder agains the actual order we have when the DetailGrid is display the first time.</remarks>
        Public Shared Sub ReorderColumns(ByVal mc As MetaDataTable)
            Dim row As DataRow
            For ii As Integer = 0 To mc.Rows.Count - 1
                row = mc.Rows(ii)
                row("pOrder") = ii
            Next
            mc.ApplyChanges()
            mc.AcceptChanges()
        End Sub
        ''' <summary>
        ''' Gnenerates the column of a MetaCommand, MetaQuery type is SELECT or TEXT
        ''' </summary>
        ''' <param name="aQueryName"></param>
        ''' <returns></returns>
        ''' <remarks>Will delete columns that are not in the SQLCommand, if not use for security</remarks>
        Public Shared Function GenerateColumnsFromSelect(ByVal aQueryName As String) As Boolean
            Try
                'GenerateColumns
                'a) using the QueryName
                '   execute the metaquery
                '   Get all Columns.
                '   scan all colunm of the data table.
                '     for each column create an according metacolumn
                '
                'the source variable
                Dim mqRequested As MetaQuery = MetaQuery.GetMetaQueryByName(aQueryName) 'the MetaQuery to with we will generate Columns
                Dim mc As MetaDataTable = New MetaDataTable ' the set of columns for that Metaquery
                Dim aQueryId As Guid

                Dim indexrow As Integer
                Dim aRow As DataRow
                'get all the columns for the corresponding Query Name
                'keep the MetaqueryId in memory to assign queryid_fk on insert
                '
                Dim dt As DataTable = mqRequested.GetSQLSchemaInfo()
                '
                aQueryId = mqRequested.QueryID
                mc.QueryName = "MetaColumns"
                mc.GetMetaCommand()
                mc.MetaCommand.SQLWhere = String.Format("QueryId_FK = '{0}'", aQueryId.ToString)
                mc.FillBusinessApplicationData()
                'Scan columns from the metaquery if exist
                mc.DefaultView.Sort = "ColumnName"
                For Each row As DataRow In dt.Rows
                    indexrow = mc.DefaultView.Find(row("ColumnName").ToString)
                    If indexrow = -1 Then
                        aRow = mc.NewRow()
                        'assign value for the metacolumn here
                        aRow("ColumnID") = Guid.NewGuid()
                        aRow("QueryID_FK") = aQueryId
                        aRow("LayoutID_FK") = CommonExt.Base.IdRepository.META_METALAYOUT_DEFAULT
                        aRow("ColumnName") = row("ColumnName").ToString
                        aRow("Split") = 0
                        aRow("pCaption_StringID_FK") = DBNull.Value
                        aRow("RoundTypeID_FK") = DBNull.Value
                        aRow("RoundFactor") = 0
                        aRow("pNumberFormatID_FK") = DBNull.Value
                        aRow("pNumberFormat") = ""
                        aRow("LOVQueryID_FK") = DBNull.Value
                        aRow("LOVAllowSharing") = False
                        aRow("TranslateQueryID_FK") = DBNull.Value
                        aRow("TRAllowSharing") = False
                        aRow("SubQueryID_FK") = DBNull.Value
                        aRow("pAlignment") = "3"
                        aRow("pAllowFocus") = True
                        aRow("pAllowSizing") = True
                        aRow("pAutoCompletion") = False
                        aRow("pAutoDropDown") = False
                        aRow("pBackColor") = ""
                        aRow("pButton") = False
                        aRow("pButtonPicture") = 0
                        aRow("ColumnGroupID_FK") = Base.IdRepository.METALIST_METACOLUMNGROUPE_VALUE
                        aRow("pDataTypeID_FK") = IdRepository.SqlDbTypeToGUID(row("DataTypeName").ToString)
                        'DataWidth
                        If row("DataType").ToString.Contains("String") Then
                            aRow("pDataWidth") = IIf(CInt(row("ColumnSize")) >= Int16.MaxValue, Int16.MaxValue, CInt(row("ColumnSize")))
                        ElseIf row("DataTypeName").ToString.Equals("bit") Then
                            aRow("pDataWidth") = 1
                        Else
                            aRow("pDataWidth") = 0
                        End If
                        aRow("pDefaultValue") = DBNull.Value
                        aRow("pEditMask") = ""
                        aRow("pEditMaskRight") = False
                        aRow("pEditMaskUpdate") = False
                        aRow("pHeadAlignment") = 3
                        aRow("pLocked") = False
                        aRow("pMerge") = False
                        aRow("pOrder") = CInt(row("ColumnOrdinal"))
                        aRow("pPresentation") = 0
                        aRow("pVisible") = 1
                        aRow("pWidth") = 200
                        aRow("pAllowGroupBy") = False
                        aRow("pGroupByOrder") = -1
                        aRow("SystemRecord") = True
                        'arow("Crtd_DT") = Now()
                        'arow("Crtd_UId") = ""
                        'arow("LUpd_DT") = Now()
                        'arow("LUpd_UId") = ""
                        'arow("RecordVersion") = ""

                        'ID, Cd, _PRM, _ALT, Inactive?
                        If row("ColumnName").ToString.ToUpper.EndsWith("ID") Or row("ColumnName").ToString = "RecordVersion" Then
                            aRow("pAllowSizing") = False
                            aRow("pVisible") = 0
                        ElseIf row("ColumnName").ToString.ToUpper.EndsWith("CD") Then
                            aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_CODE
                            aRow("pWidth") = 100
                        ElseIf row("ColumnName").ToString.ToUpper.EndsWith("_PRM") Then
                            aRow("pAllowSizing") = 1
                            If aQueryName.ToUpper.StartsWith("LOV_") Then
                                aRow("pVisible") = 2
                                aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_DESCRIPTION
                            Else
                                aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_DESCRIPTION_PRM
                            End If
                        ElseIf row("ColumnName").ToString.ToUpper.EndsWith("_ALT") Then
                            If aQueryName.ToUpper.StartsWith("LOV_") Then
                                aRow("pVisible") = 2
                                aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_DESCRIPTION
                            Else
                                aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_DESCRIPTION_ALT
                            End If
                        ElseIf row("ColumnName").ToString.ToUpper = "INACTIVE" Then
                            aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_INACTIVE
                            aRow("pWidth") = 85
                        End If

                        If row("ColumnName").ToString.ToUpper = "CRTD_DT" Then
                            aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_CRTD_DT
                            aRow("pWidth") = 85
                        ElseIf row("ColumnName").ToString.ToUpper = "CRTD_UID" Then
                            aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_CRTD_UID
                        ElseIf row("ColumnName").ToString.ToUpper = "LUPD_DT" Then
                            aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_LUPD_DT
                            aRow("pWidth") = 85
                        ElseIf row("ColumnName").ToString.ToUpper = "LUPD_UID" Then
                            aRow("pCaption_StringID_FK") = CommonExt.Base.IdRepository.META_METASTRING_LUPD_UID
                        End If
                        '
                        mc.Rows.Add(aRow)
                    Else
                        aRow = mc.DefaultView.Item(indexrow).Row
                        aRow("pDataTypeID_FK") = IdRepository.SqlDbTypeToGUID(row("DataTypeName").ToString)
                    End If
                Next

                'Scan for extra columns, not in the metaquery and delete it. 
                Dim found As Boolean
                For ii As Integer = 0 To mc.Rows.Count - 1
                    aRow = mc.Rows(ii)
                    found = False
                    For Each myRow As DataRow In dt.Rows
                        If aRow("ColumnName") = myRow("ColumnName") Then
                            found = True
                        End If
                    Next
                    If Not found AndAlso aRow("ColumnGroupID_FK") = Base.IdRepository.METALIST_METACOLUMNGROUPE_VALUE Then
                        aRow.Delete()
                    End If
                Next
                mc.ApplyChanges(reload:=False)
                Return True
            Catch ex As Exception
                Throw ex
                Return False
            End Try
        End Function

        ''' <summary>
        ''' Export to an XML files the Metaqueries with all it's MetaColumns
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function ExportMetaCommand(ByVal filename As String, ByVal queryID As Guid) As Boolean
            Using mc As MetaCommand_PL = New MetaCommand_PL("MetaQueriesExport")
                Try
                    mc.MetaDataTable.GetMetaCommand()
                    mc.MetaDataTable.MetaCommand.SQLWhere = String.Format("QueryID = '{0}'", queryID)
                    mc.InitDataForExport()
                    mc.Dataset.DataSetName = queryID.ToString
                    mc.Dataset.WriteXml(filename, XmlWriteMode.WriteSchema)
                    Return True
                Catch ex As Exception
                    Throw ex
                End Try
                Return False
            End Using
        End Function

        Public Shared Function ExportMetaCommandToMaster(ByVal queryID As Guid) As Boolean
            Dim IsSaved As Boolean
            Using mcSource As MetaCommand_PL = New MetaCommand_PL("MetaQueriesExport")
                Try
                    mcSource.MetaDataTable.GetMetaCommand()
                    mcSource.MetaDataTable.MetaCommand.SQLWhere = String.Format("QueryID = '{0}'", queryID)
                    mcSource.InitDataForExport()
                    mcSource.Dataset.DataSetName = queryID.ToString
                    For Each oTable As DataTable In mcSource.Dataset.Tables
                        For Each oRow As DataRow In oTable.Rows
                            oRow.SetAdded()
                        Next
                    Next

                    'Bypass pour ne plus utiliser la connection par défaut
                    AppManager.IsConnected = False
                    AppManager.OverrideByPassConnectionStringTOMaster = True

                    'Indique qu'elle connection utiliser dans le App.Config
                    AppManager.ConnectionConfigName = "ConnectionToMyMaster"
                    Using mcDest As MetaCommand_PL = New MetaCommand_PL("MetaQueriesExport")
                        mcDest.InitData()
                        mcDest.Dataset.Merge(mcSource.Dataset)
                        IsSaved = mcDest.Save()
                    End Using
                    Return IsSaved
                Catch ex As Exception
                    Throw ex
                Finally

                    'Remet en route la connection par défaut
                    AppManager.IsConnected = True
                    AppManager.OverrideByPassConnectionStringTOMaster = False
                    'Change pour utiliser la connection par défaut
                    AppManager.ConnectionConfigName = Nothing
                End Try
                Return False
            End Using
        End Function
        ''' <summary>
        ''' Use to exploit our xtraReport.DataSourceSchema for reporting
        ''' </summary>
        ''' <param name="filename"></param>
        ''' <param name="queryID"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function ExportXsdCommand(ByVal filename As String, ByVal queryID As Guid) As Boolean
            Using dataset As DataSet = New DataSet()
                Using mq As MetaQuery = MetaQuery.GetMetaQueryById(queryID)
                    Try
                        'on veut pas de data juste le schema du resultat
                        mq.FillResultQuery(CommandBehavior.SchemaOnly)
                        'Pour avoir le nom du DataSet dans le xsd
                        dataset.DataSetName = mq.ResultQuery.TableName
                        dataset.Tables.Add(mq.ResultQuery)
                        dataset.WriteXmlSchema(filename)
                        'OutStandingIssue: Trouver un truc pour ramener le schema dans la MetaQueries
                        Return True
                    Catch ex As Exception
                        Throw ex
                    End Try
                    Return False
                End Using
            End Using

        End Function

        ''' <summary>
        ''' Copy a  Metaqueries with all it's MetaColumns
        ''' </summary>
        ''' <remarks></remarks>
        Public Shared Sub CopyMetaCommand(ByVal queryID As Guid, ByVal queryname As String)
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPCopyMetaQuery")
                '
                sqlcmd.Parameters("@QueryID").Value = queryID
                sqlcmd.Parameters("@QueryName").Value = queryname
                '
                sqlcmd.ExecuteNonQuery()
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw sqlex
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
        End Sub

        Public Shared Sub GetRelationMetaCommand(ByVal queryID As Guid, ByVal parentID_FK As Object)
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPGetRelationMetaCommand")
                '
                sqlcmd.Parameters("@QueryID").Value = queryID
                If Not IsNothing(parentID_FK) Then
                    sqlcmd.Parameters("@ParentId_FK").Value = CType(parentID_FK, Guid)
                End If
                'Debug WriteLine
                'Console.WriteLine("@QueryID : '" & queryID.ToString & "'")
                'Console.WriteLine("@ParentId_FK : '" & parentID_FK.ToString & "'")
                '
                sqlcmd.ExecuteNonQuery()
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw sqlex
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
        End Sub

        Public Shared Sub PublishMetacommandToMetaControl(ByVal queryID As Guid)
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPMetaCommand2MetaControlPropsCRUD")
                '
                sqlcmd.Parameters("@MetaCommandID").Value = queryID
                '
                sqlcmd.ExecuteNonQuery()
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw sqlex
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
        End Sub

        Public Function InitDataForExport() As Boolean
            Dim metaDataTableChild As CommonExt.MetaDataTable
            Dim aChildRelationField As String
            Dim parentGuid As Guid = Guid.Empty
            Try
                Me.MetaDataTable.FillBusinessApplicationData()
                Me.Dataset.Tables.Add(Me.MetaDataTable)
                'ici on veux un record seulement
                If Not String.IsNullOrEmpty(Me.MetaDataTable.MetaCommand.SQLWhere) Then
                    parentGuid = CType(Me.MetaDataTable.Rows(0).Item(0), Guid)
                End If
                Dim aParentRelationField As String = Me.MetaDataTable.MetaCommand.GUIDField
                For Each row As DataRow In Me.MetaDataTable.MetaCommand.GetChildDisplayQuery.Rows
                    metaDataTableChild = New CommonExt.MetaDataTable() With {.QueryName = row("QueryName").ToString}
                    aChildRelationField = Me.MetaDataTable.MetaCommand.GUIDField & "_FK"
                    '
                    metaDataTableChild.GetMetaCommand()
                    '
                    If parentGuid <> Guid.Empty Then
                        metaDataTableChild.MetaCommand.SQLWhere = String.Format("{0} = '{1}'", aChildRelationField, parentGuid)
                    End If
                    '
                    metaDataTableChild.FillBusinessApplicationData()
                    '
                    Me.Dataset.Tables.Add(metaDataTableChild)
                    Dim aDR As New DataRelation(row("Relation").ToString, Me.MetaDataTable.Columns(aParentRelationField), metaDataTableChild.Columns(aChildRelationField))
                    Me.Dataset.Relations.Add(aDR)
                Next
                Return True
            Catch ex As Exception
                Throw ex
            End Try
            Return False
        End Function

        Public Shared Function ImportMetaCommand(ByVal fileName As String) As Boolean
            Using dset As DataSet = New DataSet()
                dset.ReadXml(fileName, XmlReadMode.ReadSchema)
                Using mc = New MetaCommand_PL("MetaQueriesExport")
                    'Hack: DataSet must be fill to have adaptercommand and merge...
                    mc.InitData()
                    mc.DataSet.Merge(dset)
                    Return mc.Save()
                End Using
            End Using
        End Function

        Public Overrides Function Delete() As Boolean
            Return False
        End Function

        Public Shared Function ValidateSQLCommand(ByVal queryName As String, ByVal queryType As System.Guid) As System.Guid
            Dim mq As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
            Try
                If queryType = IdRepository.METALIST_METACOMMANDTYPE_SP Then

                    Utils.SMOExt.ParseSQLStatement("EXECUTE sp_refreshsqlmodule '" & mq.SQLStatement & " ' ")
                Else
                    Utils.SMOExt.ParseSQLStatement(mq.SQLStatement)
                End If

                Return IdRepository.META_METAQUERY_ACT
            Catch sex As SqlException
                Return IdRepository.META_METAQUERY_SQLEX
            Catch ex As Exception
                Return IdRepository.META_METAQUERY_EXP
            End Try
        End Function


        Public Shared Sub ValidateQuery(ByVal queryName As String)
            Dim mq As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
            Try
                If mq.CommandTypeID = IdRepository.METALIST_METACOMMANDTYPE_SP Then
                    Utils.SMOExt.ParseSQLStatement("EXECUTE sp_refreshsqlmodule '" & mq.SQLStatement & " ' ")
                Else
                    Utils.SMOExt.ParseSQLStatement(mq.SQLStatement)
                End If
            Catch sex As SqlException
                Throw sex
            Catch ex As Exception
                Throw ex
            End Try
        End Sub

        Public Overrides Function Validate() As Boolean
            'Me.Validation.AddMessage("Error", "01", "Pas bon")
            'Me.Validation.AddMessage("Warning", "02", "J'ai dit Pas bon 01")
            'Me.Validation.AddValidation("Warning", "03", "Je vous l'ai tu dit Pas bon 02")
            Return True
        End Function

        Public Function BatchRecords(dataRow() As DataRow) As Boolean Implements IPLProcess.BatchRecords
            Return False
        End Function

        Public Function CurrentRecord(dataRow As DataRow) As Boolean Implements IPLProcess.CurrentRecord
            Return False
        End Function
        ''' <summary>
        ''' Will prepare new record for insert
        ''' </summary>
        ''' <param name="dataRow"></param>
        ''' <returns>Boolean</returns>
        ''' <remarks>By Default the Relation order will be set to 99 .
        ''' This is to permit assigning Relation order of child MQ as it go , either by vertical need to Client request.</remarks>
        Public Function NewRecord(dataRow As DataRow) As Boolean Implements IPLProcess.NewRecord
            dataRow("QueryID") = Guid.NewGuid
            dataRow("RelationOrder") = 99
            Return True
        End Function

        ''' <summary>
        ''' Validate a MetaCommand DataRow
        ''' </summary>
        ''' <param name="row"></param>
        ''' <remarks>By design  Mandaroty fields are verified and
        ''' some design ruels are applied
        ''' KeyID is the default value for PKColumn_Name on EXPLORER Class MQ
        '''  </remarks>
        Public Overrides Sub ValidateRow(row As DataRow)
            row.ClearErrors()
            'Mandatory Fields

            If row.Table.Columns.Contains("QueryName") Then
                If IsDBNull(row("QueryName")) Then
                    row.SetColumnError("QueryName", "Mandatory")
                End If
            End If

            If row.Table.Columns.Contains("RelationOrder") Then
                If IsDBNull(row("RelationOrder")) Then
                    row.SetColumnError("RelationOrder", "Mandatory")
                End If
            End If


            If row.Table.Columns.Contains("GUIDField") Then
                If IsDBNull(row("GUIDField")) AndAlso (row("CommandClassID_FK") = IdRepository.METALIST_METACOMMANDCLASS_READ OrElse row("CommandClassID_FK") = IdRepository.METALIST_METACOMMANDCLASS_EXPLORER) Then
                    row.SetColumnError("QueryName", "Mandatory")
                End If
            End If

            If row.Table.Columns.Contains("PKColumn_Name") Then
                If IsDBNull(row("PKColumn_Name")) AndAlso (row("CommandClassID_FK") = IdRepository.METALIST_METACOMMANDCLASS_EXPLORER) Then
                    row("PKColumn_Name") = "KeyID"
                End If
            End If

            If row.Table.Columns.Contains("FKColumn_Name") Then
                If IsDBNull(row("FKColumn_Name")) AndAlso (row("CommandClassID_FK") = IdRepository.METALIST_METACOMMANDCLASS_EXPLORER) Then
                    row("PKColumn_Name") = "ParentID"
                End If
            End If




            '
            If row.HasErrors Then
                row.RowError = "Please check your columns, a validation error occur"
            End If
        End Sub
    End Class
End Namespace

